package com.czk.yygh.order.controller;

import com.czk.yygh.common.result.Result;
import com.czk.yygh.order.service.PaymentService;
import com.czk.yygh.order.service.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/30 16:26
 */
@Api(tags = "微信支付管理")
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation(value = "生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId) {
        Map map = weiXinService.createNative(orderId);
        return Result.ok(map);
    }

    @GetMapping("/queryPayStatus/{orderId}")
    @ApiOperation(value = "查询支付订单信息")
    public Result queryPayStatus(@PathVariable Long orderId) {
        // 调用微信接口实现支付状态查询
        Map<String, String> resultMap = weiXinService.queryPayStatus(orderId);
        if (resultMap == null) {
            return Result.fail().message("支付出错");
        }
        if (Objects.equals("SUCCESS", resultMap.get("trade_state"))) {
            // 支付成功
            // 更新订单状态
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
